﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace TicketM.Configuration
{
    public partial class Escalation : System.Web.UI.Page
    {
        private string EscalationConfigPath;
        private string LocalEscalationConfigPath;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Process.GetCurrentProcess().ProcessName.ToLower().Contains("iisexpress"))
            {
                EscalationConfigPath = "/App_Data/AreaNoDaysEmails.xml";
                LocalEscalationConfigPath = "/App_Data/AreaEscalations.xml";
            }
            else
            {
                EscalationConfigPath = "/TicketM/App_Data/AreaNoDaysEmails.xml";
                LocalEscalationConfigPath = "/TicketM/App_Data/AreaEscalations.xml";
            }
            if (Session["sProject"].ToString() == "" || Session["sProject"] == null)
            {
                Session.Add("refPage", HttpContext.Current.Request.Url);
                Response.Redirect("ProjectSelection.aspx");
            }
            try
            {
                if (!Page.IsPostBack)
                {
                    TicketM.Models.Tickets areas = new Models.Tickets();
                    XmlDocument doc = areas.GetAreasStructure(Session["SProject"].ToString());
                    areas.SyncEscalationStructure(doc, Session["sProject"].ToString(),EscalationConfigPath);
                }
                AreaEscalationXml.XPath = @"//Area[@Project='" + Session["sProject"].ToString() + "']";
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                if (ex.InnerException != null)
                {
                    message += " " + ex.InnerException.Message;
                }
                Logger.CreateLogEntry("!!ERRROR in Escalation.aspx.cs while synchronizing area structure: " + message);
                Response.Redirect("../CommonErrorPage.aspx");
            }
            
        }
        
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewRow selectedRow = GridView1.SelectedRow;
            Area.Text = selectedRow.Cells[3].Text;
            EscDays.Text = selectedRow.Cells[1].Text;
            if (selectedRow.Cells[2].Text.Contains("@"))
                EscEmail.SelectedValue = selectedRow.Cells[2].Text;
            SaveButton.Enabled = true;
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(HttpContext.Current.Server.MapPath(EscalationConfigPath));
            XmlNode NodeToEdit = doc.DocumentElement.SelectSingleNode("/Area_Email_Days/Area[@Project='" + Session["sProject"].ToString() + "' and @Name='" + Area.Text + "']");
            if (NodeToEdit != null)
            {
                NodeToEdit.Attributes["Days"].Value = EscDays.Text;
                NodeToEdit.Attributes["Email"].Value = EscEmail.Text;
                try
                {
                    doc.Save(HttpContext.Current.Server.MapPath(EscalationConfigPath));
                    GridView1.DataBind();
                    result.Text = "Record Stored";
                    Logger.CreateLogEntry("** INFO Escalation Settings saved locally at " + DateTime.Now.ToString());
                }
                catch (Exception ex)
                {
                    Logger.CreateLogEntry("!!ERROR on Escalation.aspx.cs while saving the record locally. : " + ex.Message);
                    result.Text = "Error while storing the record locally. Error is logged. Please retry this operation after some time";
                }
                
                SyncBackButton.Enabled = true;
                SaveButton.Enabled = false;
            }
        }
        /// <summary>
        /// This event handler is not being used
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void SyncBackButton_Click(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(HttpContext.Current.Server.MapPath(EscalationConfigPath));
            try
            {
                doc.Save(HttpContext.Current.Server.MapPath(LocalEscalationConfigPath));
                Logger.CreateLogEntry("** INFO Escalation data synchornized at " + DateTime.Now.ToString());
            }
            catch(Exception ex)
            {
                Logger.CreateLogEntry("!!ERROR on Escalation.aspx.cs while saving the record on the server : " + ex.Message);
                Response.Redirect("../CommonErrorPage.aspx");
            }
            SyncBackButton.Enabled = false;
            SaveButton.Enabled = false;
            result.Text = "Escalation Settings Updated";
        }

        protected void EscDays_TextChanged(object sender, EventArgs e)
        {
            SaveButton.Enabled = true;
        }

        protected void EscEmail_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveButton.Enabled = true;
        }

     
    }
}